<template>
  <div>
    <el-dialog
      title="修改用户名"
      :visible.sync="open"
      :before-close="cancel"
      width="600px"
      append-to-body
    >
      <el-form ref="form" :model="form" :rules="rules" class="dialog-form">
        <el-form-item label="新用户名" prop="userName">
          <el-input v-model="form.userName" placeholder="请输入新用户名" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { updUserName } from "@/api/login";
export default {
  props: {
    open: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      form: {},
      rules: {
        userName: [{ required: true, trigger: "blur", message: "新用户名不能为空" }],
      },
    };
  },
  methods: {
    cancel() {
      this.$emit("cancel");
    },
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            const { userName } = this.form;
            await updUserName(userName);
            await this.$store.dispatch("GetInfo");
            this.$modal.msgSuccess("修改用户名成功");
          } catch (error) {
            console.error("修改用户名错误", error);
          } finally {
            this.cancel();
            this.rest();
          }
        }
      });
    },
    rest() {
      this.form = {
        userName: "",
      };
      this.resetForm("form");
    },
  },
};
</script>

<style scoped lang="scss"></style>
